package me.jiatao.wan.ui.main.system

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import me.jiatao.wan.R
import me.jiatao.wan.common.ui.LazyFragment
import me.jiatao.wan.common.ui.LoadingLottieAnimation
import me.jiatao.wan.databinding.FragmentTreeViewBinding
import me.jiatao.wan.ui.main.project.ProjectViewModel

/**
 * @Author: taojia
 * @CreateDate: 2021/9/6 2:27 下午
 * @Version: 1.0
 * @Description:
 */

@AndroidEntryPoint
class CategoryTreeFragment : LazyFragment() {

    private val mBinding by viewbind<FragmentTreeViewBinding>()
    private val projectViewModel: ProjectViewModel by viewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_tree_view, container, false)
    }

    override fun initData() {
        super.initData()


        /** 获取分类列表 */
        projectViewModel.loadingState.observe(viewLifecycleOwner) { state ->
            mBinding.apply {
                loadingLayout.lottieAnimation.status = state
                loadingLayout.retryButton.isVisible = state == LoadingLottieAnimation.State.ERROR
            }
        }

        mBinding.loadingLayout.retryButton.setOnClickListener { _ ->
            loadData()
        }

        loadData()
    }

    private fun loadData() {
        if (projectViewModel.categoryTreeAdapter==null){
            projectViewModel.fetchCategoryTreeVM().observe(viewLifecycleOwner) { categoryList ->
                projectViewModel.categoryTreeAdapter = CategoryTreeAdapter(categoryList)

                mBinding.recyclerView.adapter = projectViewModel.categoryTreeAdapter
            }
        }else{
            mBinding.recyclerView.adapter = projectViewModel.categoryTreeAdapter
        }
    }
}